#!/bin/bash
# compile cross-compiler

SCRIPT_DIR=$(pwd)

if [ $LOG ] ; then
	exec &>${0##*/}.log
fi

#
# 2018-03-06
#
# The following is a non-exhaustive list of $(TARGET) tuples that are believed to work:
#	aarch64[_be]-linux-musl
#	arm[eb]-linux-musleabi[hf]
#	i*86-linux-musl
#	microblaze[el]-linux-musl
#	mips-linux-musl
#	mips[el]-linux-musl[sf]
#	mips64[el]-linux-musl[n32][sf]
#	powerpc-linux-musl[sf]
#	powerpc64[le]-linux-musl
#	s390x-linux-musl
#	sh*[eb]-linux-musl[fdpic][sf]
#	x86_64-linux-musl[x32]
#

TARGETS_32BIT='
arm-linux-musleabihf
i686-linux-musl
'

ALL_SUPPORTED_TARGETS='
arm-linux-musleabihf
i686-linux-musl
x86_64-linux-musl
aarch64-linux-musl
'

for app in gcc make git ; do
	if ! $app --version &>/dev/null ; then
		echo -e "\033[1;31m""$app is not installed""\033[0m"
		exit 1
	fi
done

#---

OPT=$1

case $(uname -m) in
	*64*)  ALL_TARGETS="$ALL_SUPPORTED_TARGETS" ;;
	*) ALL_TARGETS="$TARGETS_32BIT" ;;
esac

if [ "$OPT" = "auto" -o "$OPT" = "all" ] ; then
	TARGETS=$ALL_TARGETS
elif [ "$OPT" ] ; then
	for i in $ALL_TARGETS ; do
		case $i in
			"$OPT"*) TARGETS=$i ; break;;
		esac
	done
fi

if [ -z "$TARGETS" ] ; then
	echo "Need a target:"
	echo "$ALL_TARGETS"
	exit 1
fi

if [ ! -d musl-cross-make ] ; then
	git clone git://github.com/richfelker/musl-cross-make.git musl-cross-make
fi
if [ ! -d musl-cross-make ] ; then
	echo "ERROR"
	exit 1
fi

cp -f z_config.mak musl-cross-make/config.mak

#-----------------

for TG in $TARGETS
do

	cd "$SCRIPT_DIR"

	echo -----------------------------------------
	echo $TG
	echo -----------------------------------------

	DATE=$(date "+%Y%m%d")
	TARCH=$(echo $TG | cut -f1 -d '-')
	CC_DIR=cross-compiler-${TARCH}
	CC_PKG=${CC_DIR}-${DATE}.tar.xz

	#echo $CC_DIR
	#echo $CC_PKG

	cd musl-cross-make

	INSTALL_DIR=$(pwd)/${CC_DIR}
	mkdir -p $INSTALL_DIR

	make clean
	make OUTPUT="$INSTALL_DIR" TARGET="$TG" install && \
	tar -Jcf "$CC_PKG" "$CC_DIR"

	mkdir -p ../0sources
	mv -fv "$CC_PKG" ../0sources

	echo "Done !"

done

### END ###
